//1.添加material依赖
import 'package:flutter/material.dart';
import 'package:power_house/scoped_model/auth.dart';
import 'package:power_house/util/common_toast.dart';
import 'package:power_house/util/dio_http.dart';
import 'package:power_house/util/scoped_model_helper.dart';
import 'package:power_house/util/store.dart';
import 'package:power_house/util/string_util.dart';

import '../config.dart';

//2.编写无状态组件
class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool showPassword = false;
  TextEditingController usernameTextController = TextEditingController();
  TextEditingController passwordTextController = TextEditingController();

  _login() async {
    var username = usernameTextController.text;
    var password = passwordTextController.text;
    if (stringIsNullOrEmpty(username)) {
      CommonToast.showToast("用户名不能为空");
      return;
    }
    if (stringIsNullOrEmpty(password)) {
      CommonToast.showToast("密码不能为空");
      return;
    }
    // const loginUrl = '${Config.baseUrl}/user/login';
    const loginUrl = '${Config.baseUrl}/user/login';
    var params = {
      'username': username,
      'password': password,
    };
    var response = await DioHttp.of(context).post(loginUrl, params);
    var resMap = response.data;
    if (resMap == null) {
      return;
    }
    int status = resMap['code'];
    bool isSuccess = resMap['data']['isSuccess'];
    String message = resMap['data']['message'] ?? '未知错误';
    if (!isSuccess) {
      CommonToast.showToast(message);
      return;
    }
    CommonToast.showToast(message);
    if (status == 200) {
      String token = resMap['data']['body']['token'];
      var store = await Store.getInstance();
      await store.setString(StoreKeyList.loginToken, token);
      if (context.mounted) {
        ScopedModelHelper.getModel<AuthModel>(context).login(token, context);
      }
      if (context.mounted) {
        Navigator.of(context).pop();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
      ),
      body: SafeArea(
        minimum: const EdgeInsets.all(30),
        child: ListView(
          children: <Widget>[
            const Padding(padding: EdgeInsets.all(10)),
            TextField(
              controller: usernameTextController,
              decoration: const InputDecoration(
                labelText: '用户名',
                hintText: '请输入用户名',
              ),
            ),
            const Padding(padding: EdgeInsets.all(10)), //padding
            TextField(
              controller: passwordTextController,
              obscureText: !showPassword,
              decoration: InputDecoration(
                  labelText: '密码',
                  hintText: '请输入密码',
                  suffixIcon: IconButton(
                      onPressed: () {
                        setState(() {
                          showPassword = !showPassword;
                        });
                      },
                      icon: Icon(showPassword ? Icons.visibility : Icons.visibility_off))),
            ),
            const Padding(padding: EdgeInsets.all(10)), //padding
            ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.green),
                ),
                onPressed: () {
                  _login();
                },
                child: const Text(
                  '登录',
                  style: TextStyle(color: Colors.white),
                )),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text('还没有账号'),
                TextButton(
                    onPressed: () {
                      Navigator.pushReplacementNamed(context, "/register");
                    },
                    child: const Text(
                      '去注册',
                      style: TextStyle(color: Colors.green),
                    ))
              ],
            )
          ],
        ),
      ),
    );
  }
}
